#include "call_python.h"
#include <iostream>
#include <stdlib.h> 
#include "cpp_python_expand.h"
#define PY_SSIZE_T_CLEAN
#include <python3.8/Python.h>  //调用Python2.7
#define SPAM_MODULE

using namespace std;

CallPython::CallPython()
{
	Py_Initialize();
}
CallPython::~CallPython()
{
	Py_Finalize();
}

void CallPython::CallFunction(std::string func)
{
    PyRun_SimpleString(func.c_str());
}
void CallPython::CallFile(std::string name)
{
    //PyRun_SimpleString("import sys");
    //PyRun_SimpleString("sys.path.append('./')");
	wchar_t* path = L"./";
    PySys_SetPath(path);

    // 加载模块
    PyObject* pModule = PyImport_ImportModule("test"); //模块名，不是文件名
    //PyObject* pModule = PyImport_Import(moduleName);
    if (!pModule) // 加载模块失败
    {
        cout << "[ERROR] Python get module failed." << endl;
        return ;
    }
    cout << "[INFO] Python get module succeed." << endl;

    // 加载函数
    PyObject* pv = PyObject_GetAttrString(pModule, "test_add");
    if (!pv || !PyCallable_Check(pv))  // 验证是否加载成功
    {
        cout << "[ERROR] Can't find funftion (test_add)" << endl;
        return ;
    }
    cout << "[INFO] Get function (test_add) succeed." << endl;

    // 设置参数
	/*
    PyObject* args = PyTuple_New(2);   // 2个参数
    PyObject* arg1 = PyInt_FromLong(4);    // 参数一设为4
    PyObject* arg2 = PyInt_FromLong(3);    // 参数二设为3
    PyTuple_SetItem(args, 0, arg1);
    PyTuple_SetItem(args, 1, arg2);
	*/
	PyObject* args = Py_BuildValue("ii", 2, 3);

    // 调用函数
    PyObject* pRet = PyObject_CallObject(pv, args);
	Py_DECREF(args);
    // 获取参数
    if (pRet )  // 验证是否调用成功
    {
		//PyObject* pVulNameObj = PyTuple_GetItem(pRet, 0);
        long result = PyLong_AsLong(pRet);
        cout << "result:" << result <<endl;
    }

}
void CallPython::Test()
{
    CppPythonExpand::GetMe().Run();
	wchar_t* program = Py_DecodeLocale("test.py", NULL);
	if (program == NULL) {
		fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
		exit(1);
	}

	Py_SetProgramName(program);

    CallFunction("print('hello world')");
 
	CallFile(".");
	PyMem_RawFree(program);
}
